<template>
  <view class="page">
    <Navbar title="商品详情" />
    <u-sticky customNavHeight="0" z-index="6">
      <u-swiper
        :list="goods.images"
        height="248"
        radius="0"
        circular
        interval="5000"
        @click="preImage"
      />
    </u-sticky>
    <view class="body">
      <view class="price">
        <view>
          ￥ <text>{{ goods.sku[0].price }}</text>
        </view>
        <view>
          ￥<text>{{ goods.sku[0].market_price }}</text>
        </view>
      </view>
      <Sub-title :label="goods.title" size="28rpx" />
      <view class="base">
        <u-icon
          name="map-fill"
          color="#BABABA"
          size="24rpx"
          :label="goods.shop.city ? goods.shop.city.split('/')[1] : '中国'"
          label-color="#BABABA"
          label-size="24rpx"
        />
        <text> 快递费：¥{{ goods.freight.price || 0 }} </text>
        <text> 已售：{{ goods.sales || 0 }} </text>
      </view>
      <Sub-title
        :label="`宝贝评论(${goods.comment || 0})`"
        size="28rpx"
        :bold="false"
        :right-text="`${
          goods.comment > 0 ? parseInt((goods.praise / goods.comment) * 100) : 0
        }%好评率>`"
        right-color="#FF8528"
        @clickRight="onTag('')"
      />
      <view class="c-row">
        <view @click="onTag('good')">好评 ({{ goods.praise || 0 }}) </view>
        <view @click="onTag('pertinent')">中评 ({{ goods.moderate || 0 }}) </view>
        <view @click="onTag('poor')">差评 ({{ goods.negative || 0 }}) </view>
        <view @click="onTag('figure')">有图 ({{ goods.comment_list.figure || 0 }}) </view>
      </view>
      <!-- <view class="comment-box" v-for="item in goods.comment_list.data" :key="item.id">
        <view class="userinfo">
          <view class="avatar">
            <u-avatar :src="item.user.avatar" size="35" />
            <view style="margin-left: 20rpx">
              <u-text
                :text="item.user.nickname || '用户昵称'"
                size="13"
                color="#222"
                lines="1"
              />
            </view>
          </view>
          <u-rate
            :count="5"
            v-model="item.score"
            readonly
            size="16"
            gutter="2"
            active-color="#ff4e02"
            inactive-color="#cad0cc"
          />
        </view>
        <view class="details">
          <u-text :text="item.content" size="14" color="#222" line-height="40" />
          <u-text :text="`规格：${item.suk}`" size="14" color="#aaa" line-height="25" />
        </view>
        <view>
          <u-album :urls="item.images" multiple-size="215rpx" />
        </view>
      </view> -->
      <Card-item
        :image="shop.avatar"
        image-size="112rpx"
        :title="shop.shopname"
        :bold="false"
        :sub-title="`${shop.service_ids.map((i) => {
          return i.name;
        })}`"
        @click="handleShopInfo"
      />
      <Sub-title label="产品详情" size="28rpx" :bold="false" />
      <u-parse :content="goods.content" :domain="domain" useAnchor />
    </view>
    <view class="btn">
      <view class="flex">
        <u-icon
          :name="require('@/static/mall/cart-buy.png')"
          size="32rpx"
          label="购物车"
          label-color="#555555"
          label-size="24rpx"
          label-pos="bottom"
          @click="handleCart"
        />
        <u-icon
          :name="require('@/static/mall/service-buy.png')"
          size="32rpx"
          label="客服"
          label-color="#555555"
          label-size="24rpx"
          label-pos="bottom"
          @click="handleService"
        />
      </view>
      <view class="buy">
        <view class="btn-group">
          <view class="btn-left" @click="handleAddCart">加入购物车</view>
          <view class="btn-right" @click="handleShop">立即购买</view>
        </view>
      </view>
    </view>
    <u-popup
      :show="skuShow"
      closeable
      close-on-click-overlay
      round="10"
      @close="closeSku"
    >
      <view class="s-row">
        <u-image
          show-loading
          :src="goods.images[0]"
          :show-menu-by-longpress="false"
          width="208rpx"
          height="208rpx"
          radius="10rpx"
        />
        <view class="s-right">
          <view class="s-price">
            <text class="text-price" />
            {{ goods.price }}
          </view>
          <view v-if="selectList.length">
            库存 <text class="margin-lr-xs">{{ selectshop.stock || 0 }}</text> 件
          </view>
          <view v-if="selectList.length">
            <text style="color: #222"> 已选择 </text>
            <text v-for="name in selectList" style="color: #222; margin-right: 10rpx">
              {{ name }}
            </text>
          </view>
          <view v-else>
            <text style="color: #222"> 请选择： </text>
            <text v-for="(s, sk) in goods.spu" :key="s.id" style="color: #979797">
              <block v-if="sk != 0">-</block>
              {{ s.name }}
            </text>
          </view>
        </view>
      </view>
      <scroll-view scroll-y style="max-height: 500rpx; box-sizing: border-box">
        <view v-for="(spu, sk) in goods.spu" :key="spu.id" class="spu-item">
          <view>{{ spu.name }}</view>
          <view class="spu-tag">
            <view
              class="cu-tag"
              v-for="(item, index) in spu.item"
              :key="index"
              :class="{
                active: selectIndex[sk] == index,
                noactive: item.isShow,
              }"
              @click="skuClick(item, sk, index)"
            >
              {{ item.name }}
            </view>
          </view>
        </view>
        <view class="s-end">
          <view>购买数量</view>
          <view>
            <u-number-box
              v-model="selectNum"
              :min="1"
              :max="selectshop.stock"
              :disabled="canCount"
              @change="changeNum"
            >
              <view slot="minus">
                <u-icon
                  name="minus-circle-fill"
                  size="30"
                  :color="canCount ? '#eaeaea' : '#B8B8B8'"
                />
              </view>
              <text slot="input" style="width: 50px; text-align: center">
                {{ selectNum || 0 }}
              </text>
              <view slot="plus">
                <u-icon
                  name="plus-circle-fill"
                  size="30"
                  :color="canCount ? '#eaeaea' : '#B8B8B8'"
                />
              </view>
            </u-number-box>
          </view>
        </view>
      </scroll-view>
      <view class="add-btn">
        <u-button
          type="primary"
          shape="circle"
          color="#3BA199"
          text="完成"
          :throttle-time="1000"
          @click="handleBuy"
        />
      </view>
    </u-popup>
  </view>
</template>

<script>
import Navbar from "@/components/Navbar/index";
import CardItem from "@/components/CardItem/index";

import config from "@/request/baseUrl.js";
import { mallGoodsDetail, mallReCart, mallSkuStock } from "@/request/mallApi.js";

export default {
  components: { Navbar, CardItem },
  data() {
    return {
      domain: config.baseUrl,
      goodsId: 0, // 商品ID
      shop: {}, // 店铺信息
      height: 0, // 图片高度
      goods: {},
      skuShow: false, // 规格弹窗
      selectList: [], // 选择规格label
      selectIndex: [], // 选择规格value
      selectshop: {}, //存放最后选中的商品
      selectNum: 1, //选中数量
      canCount: false, // 是否禁止选择数量
    };
  },
  onLoad(e) {
    this.goodsId = e.id;
    this.getData();
  },
  watch: {
    selectshop: {
      handler(v) {
        if (v?.id) {
          this.canCount = false;
        } else {
          this.canCount = true;
          this.selectNum = 1;
        }
      },
      immediate: true,
      deep: true,
    },
  },
  // 监听页面滚动
  onPageScroll(scroll) {
    uni.$emit("onPageScroll", scroll.scrollTop);
  },
  methods: {
    // 预览图片
    preImage(index) {
      console.log(index);
      uni.previewImage({
        current: index,
        urls: this.goods.images,
      });
    },
    // 获取商品详情
    getData() {
      mallGoodsDetail({ id: this.goodsId }).then((res) => {
        if (res.code == 1) {
          let images = res.data.images.map((i) => {
            return config.baseUrl + i;
          });
          res.data.images = images;
          this.goods = res.data;
          // 店铺信息
          let shop = res.data.shop;
          shop.avatar = config.baseUrl + shop.avatar;
          this.shop = shop;
        }
      });
      uni.getImageInfo({
        src: this.goods.coverPath,
        success: (image) => {
          let bl = image.width / image.height; // 图片宽高比
          let wInfo = uni.getWindowInfo();
          this.height = wInfo.screenWidth / bl;
        },
      });
    },
    // 查看评论
    onTag(tag) {
      uni.navigateTo({
        url: `/pages/mall/goodsComment?id=${this.goods.id}&tag=${tag}`,
      });
    },
    // 跳转店铺
    handleShopInfo() {
      uni.navigateTo({ url: `/pages/mall/goodsShop?id=${this.goods.shop_id}` });
    },
    // 联系客服
    handleService() {
      this.$author(() => {
        this.$toChat(this.goods.shop_id, {
          id: this.goods.id,
          title: this.goods.title,
          image: this.goods.image,
          price: this.goods.price,
        });
      });
    },
    // 跳转购物车
    handleCart() {
      this.$author(() => {
        uni.navigateTo({ url: `/pages/mall/goodsCart` });
      });
    },
    // 关闭规格弹窗
    closeSku() {
      this.skuShow = false;
    },
    //商品规格修改数量
    changeNum(val) {
      if (this.selectshop.stock) {
        let num = parseInt(val);
        if (num > this.selectshop.stock) {
          uni.showToast({
            title: "数量已达上限",
            icon: "none",
          });
          this.selectNum = parseInt(this.selectshop.stock);
        } else {
          this.selectNum = parseInt(val);
        }
      }
    },
    // 商品规格组合 选择
    skuClick(value, sk, index) {
      // if (value.isShow) {
      if (this.selectList[sk] != value.name) {
        this.selectList[sk] = value.name;
        this.selectIndex[sk] = index;
      } else {
        this.selectList[sk] = "";
        this.selectIndex[sk] = -1;
      }
      this.$forceUpdate();
      //如果全部选完
      if (this.selectList.every((item) => item != "")) {
        let str = this.selectList.join(",");
        this.selectshop = this.goods.sku.find((s) => s.difference.join(",") == str);
        this.loadStock(this.selectshop.id);
        this.selectNum = 1;
      }
      if (this.selectList.every((item) => !item)) {
        this.selectList = [];
        this.selectIndex = [];
        this.selectshop = {};
      }
      // }
    },
    loadStock(sku_id) {
      mallSkuStock({ sku_id }).then((res) => {
        if (res.code == 1) {
          this.selectshop.stock = res.data;
        }
      });
    },
    // 加入购物车
    handleAddCart() {
      this.action = "cart";
      this.skuShow = true;
    },
    // 单独购买
    handleShop() {
      this.action = "buy";
      this.skuShow = true;
    },
    // 清空已选旧数据
    cleanSku() {
      this.skuShow = false;
      this.selectList = [];
      this.selectIndex = [];
      this.selectshop = {};
    },
    // 跳转购买
    handleBuy() {
      if (this.action == "cart") {
        if (this.selectList.every((item) => !item)) {
          uni.showToast({
            title: "请选择商品规格",
            icon: "none",
          });
          return;
        }
        this.$author(() => {
          let { shop_id, shop, id, title, image, sku } = this.goods;
          let data = {
            data: {
              shop_id: shop_id,
              shop_name: shop.shopname,
              goods_id: id,
              title: title,
              number: this.selectNum,
              image: image,
              sku: sku[0],
              sku_id: sku[0].id,
              sum: this.$bcmul(this.selectshop.price, this.selectNum),
            },
            type: "add",
          };
          mallReCart(data).then((res) => {
            if (res.code == 1) {
              uni.showToast({
                title: "添加成功",
                icon: "success",
                success: () =>{
                  setTimeout(() => {
                    let route = this.$prePage().$scope.route;
                    if (route == "pages/mall/goodsCart") {
                      this.$prePage().getDataList();
                    }
                  }, 1500)
                }
              });
              
              this.cleanSku();
            }
          });
        });
      } else if (this.action == "buy") {
        if (!this.selectshop.id) {
          uni.showToast({
            title: "请选择商品规格",
            icon: "none",
          });
          return;
        }
        this.$author(() => {
          var data = [
            {
              goods_id: this.goods.id,
              number: this.selectNum,
              sku_id: this.selectshop.id,
            },
          ];
          uni.navigateTo({
            url: `/pages/mall/goodsOrder?data=${JSON.stringify(data)}`,
          });
          this.cleanSku();
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  .body {
    width: 100%;
    padding: 20rpx 20rpx 200rpx 20rpx;
    z-index: 8;
    min-height: 100rpx;
    box-sizing: border-box;
    background-color: #ffffff;
    margin-top: -80rpx;
    border-radius: 40rpx 40rpx 0 0;
    position: relative;
    .price {
      display: flex;
      color: #ff8528;
      align-items: flex-end;
      > view:nth-child(1) {
        font-weight: 600;
        font-size: 50rpx;
      }
      > view:nth-child(2) {
        font-size: 32rpx;
        margin-left: 10rpx;
        margin-bottom: 6rpx;
        text-decoration: line-through;
      }
    }
    .base {
      font-size: 24rpx;
      color: #bababa;
      display: flex;
      padding-bottom: 30rpx;
      border-bottom: 1rpx solid #d9d9d999;
      justify-content: space-between;
      .u-icon,
      > text {
        margin-right: 40rpx;
      }
    }
    .c-row {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      padding-bottom: 20rpx;
      border-bottom: 1rpx solid #d9d9d999;
      > view {
        color: #979797;
        font-size: 28rpx;
        border-radius: 40rpx;
        background-color: #f6f6fb;
        padding: 8rpx 22rpx;
        margin-right: 20rpx;
        &:last-child {
          margin-right: 0;
        }
      }
    }
    // // 详情页不展示评论
    // .comment-box {
    //   margin: 25rpx 0;
    //   background-color: #fff;
    //   padding: 20rpx;
    //   border-bottom: 1rpx solid #d9d9d999;
    //   .userinfo {
    //     display: flex;
    //     justify-content: space-between;
    //     align-items: center;
    //     .avatar {
    //       display: flex;
    //       align-items: center;
    //     }
    //   }
    //   .details {
    //     margin: 20rpx 0;
    //   }
    //   .goods {
    //     background-color: #f5f5f5;
    //     display: flex;
    //     align-items: center;
    //     .cu-avatar {
    //       width: 120rpx;
    //       height: 120rpx;
    //     }
    //     .content {
    //       width: calc(100% - 145rpx);
    //     }
    //   }
    // }
  }
  .btn {
    position: fixed;
    background-color: #fff;
    box-shadow: 0 0 8rpx rgba(0, 0, 0, 0.05);
    display: flex;
    height: 126rpx;
    padding: 20rpx;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 9;
    .flex {
      flex: 1;
      display: flex;
      justify-content: space-around;
    }
    .buy {
      width: 400rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      .btn-group {
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-size: 28rpx;
        > view {
          width: 188rpx;
          height: 80rpx;
          text-align: center;
          line-height: 80rpx;
        }
        .btn-left {
          background-color: #89c7c2;
          border-radius: 40rpx 0 0 40rpx;
          &:active {
            background-color: #7ab5b0;
          }
        }
        .btn-right {
          background-color: $active-color;
          border-radius: 0 40rpx 40rpx 0;
          &:active {
            background-color: #328a83;
          }
        }
      }
    }
  }
}
.s-row {
  display: flex;
  padding: 20rpx;
  justify-content: flex-start;
  border-bottom: 1rpx solid #ececec;
  .s-right {
    flex: 1;
    height: 208rpx;
    margin-left: 20rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    overflow: hidden;
    > view {
      font-size: 28rpx;
      line-height: 60rpx;
    }
    .s-price {
      color: #fe6600;
      font-size: 36rpx;
      .text-price::before {
        content: "¥";
        font-size: 80%;
        margin-right: 4rpx;
      }
    }
  }
}
.spu-item {
  border-bottom: 1rpx solid #ececec;
  padding: 20rpx;
}
.s-end {
  display: flex;
  justify-content: space-between;
  padding: 20rpx;
}
.spu-tag {
  display: flex;
  flex-wrap: wrap;
  .cu-tag {
    font-size: 26rpx;
    vertical-align: middle;
    position: relative;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
    padding: 0 26rpx;
    height: 66rpx;
    font-family: Helvetica Neue, Helvetica, sans-serif;
    white-space: nowrap;
    margin-right: 26rpx;
    margin-top: 20rpx;
    background-color: #f6f6f6;
    border-radius: 12rpx;
    color: #222;
  }
  .active {
    color: #eb5d2a;
    background-color: #fdf9f9;
  }
  .noactive {
    color: #cacaca;
    background-color: #efefef;
  }
}
.add-btn {
  padding: 20rpx;
}
</style>
